<template>
  <!-- 核心数据 卡片 -->
  <div class="chart-box">
    <el-row :gutter="24" class="item">
      <el-col :span="6" style="overflow: hidden;">
        <slot></slot>
      </el-col>

      <el-col v-for="(item , index) in opList" v-if="item!=='localSpendAmount'" :span="6">

        <div class="op-box">
          <!-- 头部 -->
          <div class="flex box-header">
            <!-- 标题 -->
            <div class="lt">
              <span class="webfont-Medium pointer" @click="handleOpenDetail(item)">{{ setItem(item).label }}</span>
              <el-tooltip class="item" effect="dark" :content="setItem(item).sec" placement="top">
                <i class="el-icon-warning" @click.stop="()=>{}" />
              </el-tooltip>
            </div>
            <!-- 切换 -->
            <div class="rt">
              <el-popover :ref="'popover'+index" width="200" trigger="click">
                <div class="op-list">
                  <template v-for="v in echartsOptions">
                    <div
                      v-if="v.val!=='localSpendAmount'"
                      :class="v.val===item?'op-item pointer active':'op-item pointer '"
                      @click="handleChangeOP(index,v.val)"
                    >
                      <i class="el-icon-check"></i>
                      <span>{{ v.name==='下载'?'安装':v.name }}</span>
                    </div>
                  </template>
                </div>
                <i slot="reference" class="el-icon-sort"></i>
              </el-popover>
            </div>
          </div>

          <div class="main pointer" @click="handleOpenDetail(item)">
            <div class="num">
              <!-- {{ cardData.now[item] }} -->
              <!-- 如果是点击，展示，下载，安装； 则为整数  不显示小数 -->

              <countTo
                v-show="item==='impressions'||item==='taps'||item==='installs'||item==='newDownloads'||item==='redownloads'||item==='latOninstalls'||item==='latOffinstalls'"
                :start-val="0"
                :end-val="cardData.now[item]*1||0"
                :duration="1500"
                class="main-num "
                :decimals="0"
              />

              <!-- 如果是转化率，点击率，则乘以100，显示小数及百分比 -->
              <countTo
                v-show="item==='conversionRate'||item==='ttr'"
                :start-val="0"
                :end-val="cardData.now[item]*100*1||0"
                :duration="1500"
                class="main-num "
                :decimals="2"
                suffix="%"
              />

              <!-- 如果是CPT或者是CPA -->
              <div v-show="item==='avgCptAmount'||item==='avgCpaAmount'" class="flex num" style="justify-content: flex-start;">
                <span>{{ unit==='USD'?'$':'￥' }}</span>
                <countTo :start-val="0" :end-val="cardData.now[item]*1||0" :decimals="2" :duration="1500" class="main-num " />
              </div>

            </div>
            <div class="pointer">
              <chart-index :chart-data="echartInfo" :prop-index="item" style="max-width: 100%;overflow: hidden;"></chart-index>
            </div>

          </div>

          <div class="footer flex">
            <div v-if="item==='impressions'||item==='taps'||item==='installs'" class="rt  ping-jun">
              <el-tooltip class="item" effect="dark" :content="startTime+'至'+endTime+'的日均值'" placement="top">
                <span class="title default" style="margin-right: 8px;">日均{{ setItem(item).label }}</span>
              </el-tooltip>

              <span>{{ getPingJun(item) }}</span>

            </div>
            <div v-else class="huang-bi">
              <huang-bi :new-val="cardData.now[item]*1" :old-val="cardData.old[item]*1" title="环比" :content="'对比'+lastCycle[0]+'至'+lastCycle[1]"></huang-bi>
            </div>
            <!-- 日环比开始 -->
            <!-- <div v-if="dayRingShow" class="day-huang-bi">
              <huang-bi
                :new-val="cardData.yesterday[item]*1"
                :old-val="cardData.dayBeforeYesterday[item]*1"
                title="日环比"
                :content="'昨日对比'+beforeYesterday"
              ></huang-bi>
            </div> -->
            <!-- 日环比结束 -->
          </div>

        </div>

      </el-col>
    </el-row>
    <attrDetail :visible.sync="dialogFormVisible" :type-str="dialogType"></attrDetail>
  </div>
</template>
<script>
import {
  echartsOptions
} from '@/settings.js'
import {
  getsLastPeriod,
  getBeforeYes,
  includeTime

} from '@/utils/moment.js'

import countTo from 'vue-count-to'
import chartIndex from './chart.vue'
import huangBi from '@/components/huangBi/index.vue'
import attrDetail from './attrDetail.vue'
export default {
  name: '', // ·������
  components: {
    chartIndex,
    countTo,
    huangBi,
    attrDetail
  },
  props: {

    cardData: {
      type: Object,
      default: () => {
        return []
      }
    },
    echartInfo: {
      type: Object,
      default: () => {
        return []
      }
    },
    startTime: {
      type: String
    },
    endTime: {
      type: String
    },
    unit: {
      type: String,
      default: function() {
        const unit = this.$store.state.user.unit
        if (unit === 'USD') {
          this.pre = '$'
        } else {
          this.pre = '￥'
        }
        return this.$store.state.user.unit
      }
    }
  },
  data() {
    return {
      echartsOptions: [
        ...echartsOptions,
        {
          name: '新增下载次数',
          val: 'newDownloads'
        }, {
          name: '重新下载次数',
          val: 'redownloads'
        }, {
          name: '开启LAT下载',
          val: 'latOninstalls'
        }, {
          name: '关闭LAT下载',
          val: 'latOffinstalls'
        }
      ],
      pre: '$',
      opList: [],
      handleList: [],
      dialogFormVisible: false,
      dialogType: undefined
    }
  },
  computed: {
    // 上个周期的值
    lastCycle() {
      const that = this
      if (this.startTime && this.endTime) {
        return getsLastPeriod([this.startTime, this.endTime])
      }
    },
    beforeYesterday() {
      return getBeforeYes()
    },
    dayRingShow() {
      return includeTime(this.endTime)
    }

  },
  watch: {

    echartInfo: { // �����Ķ���
      deep: true, // ���ȼ�������Ϊ true
      immediate: true,
      handler: function(newV, oldV) {
      }
    },

    cardData: { // �����Ķ���
      deep: true, // ���ȼ�������Ϊ true
      immediate: true,
      handler: function(newV, oldV) {
      }
    }

  },
  // ������
  created() {
    const arr = localStorage.getItem('YYY_TYPE_EOP') ? JSON.parse(localStorage.getItem('YYY_TYPE_EOP')) : []
    if (!arr.length) {
      const list = []
      this.echartsOptions.forEach(item => {
        if (item.val !== 'localSpendAmount' && list.length < 7) {
          return list.push(item.val)
        }
      })
      this.opList = list
    } else {
      this.opList = JSON.parse(JSON.stringify(arr))
    }

    this.handleList = this.opList.map(item => {
      return {
        visible: false
      }
    })
  },
  // ���غ�
  mounted() {

  },
  // ���ٺ�
  destroyed() {

  },

  // ����
  methods: {

    // 计算平均值
    getPingJun(val) {
      let dayNum = 1
      if (this.echartInfo.length && this.echartInfo[0].date.length < 11) {
        dayNum = this.echartInfo.length
      } else {
        dayNum = this.echartInfo.length / 24 < 1 ? 1 : this.echartInfo.length / 24
      }

      let num = 0
      this.echartInfo.forEach(item => {
        num += item[val]
      })
      return (num * 100 / (dayNum * 100)).toFixed(2)
    },

    // 打开详情
    handleOpenDetail(type) {
      this.dialogType = type
      this.dialogFormVisible = true
    },

    // 设置显示名称及提示语
    setItem(val) {
      const i = this.echartsOptions.findIndex(item => {
        return item.val === val
      })
      let label = ''
      switch (this.echartsOptions[i].name) {
        case 'CPT':
          label = '平均每次点击费用(CPT)'
          break
        case 'CPA':
          label = '平均每次转化费用(CPA)'
          break
        case '下载':
          label = '安装'
          break
        default:
          label = this.echartsOptions[i].name
      }
      let sec = `${this.startTime}至${this.endTime}${label}`
      if (label === '安装' || label === '展示' || label === '点击' || label === '下载') {
        sec += '数总和'
      }

      const obj = {
        ...this.echartsOptions[i],
        label,
        sec
      }

      return obj
    },

    // 切换选项
    handleChangeOP(index, val) {
      this.$set(this.opList, index, val)
      this.handleList[index].visible = false
      this.$refs['popover' + index][0].doClose()
      window.localStorage.setItem('YYY_TYPE_EOP', JSON.stringify(this.opList))
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped lang="scss">
  @import "~@/styles/variables.scss";

  .chart-box {
    .el-row {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      flex-wrap: wrap;
    }

    .el-col-6 {
      max-width: calc(25% - 1px);
      overflow: hidden;
    }

    .op-box {
      background: #FFFFFF;
      border-radius: 4px;
      padding: 16px;
      margin-bottom: 24px;
      max-width: calc(100% - 1px);
      overflow: hidden;

      .box-header {
        padding-bottom: 24px;
        max-width: 100%;
        overflow: hidden;

        .lt {
          font-size: 14px;

          i {
            margin-left: 6px;
            color: #c4c4c4;
          }
        }

        .rt {
          font-size: 14px;

          i {
            transform: rotate(270deg);
            font-weight: 700;
            color: #c4c4c4;
          }

        }
      }

      .main {
        min-height: 80px;

        .num {
          color: #000;
          font-size: 24px;
          line-height: 24px;
          font-family: Roboto-Bold, PingFangSC-Medium, PingFangSC, sans-serif !important;
        }
      }

      .footer {
        border-top: 1px solid rgba(57, 68, 78, .1);
        padding-top: 16px;
        font-size: 12px;
        line-height: 18px;

        .title {
          color: rgb(172, 182, 194);
          font-size: 12px;
        }

        .huangbi,
        .day-huangbi {
          div {
            display: inline-block;
          }
        }

      }
    }
  }

  .op-list .op-item {
    font-size: 14px;
    margin-bottom: 12px;

    i {
      margin-right: 8px;
      font-size: 12px;
      font-weight: 600;
      color: $mainColor1;
      opacity: 0;
    }

    &.active,
    &:hover {
      i {
        opacity: 1;
      }
    }

  }
</style>
